package com.gitee.andy.zpush.kernel;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.DefaultThreadFactory;

public final class TcpServer {
	private EventLoopGroup bossGroup;
	private EventLoopGroup workerGroup;
	private static final Logger log = LoggerFactory.getLogger(TcpServer.class);

	public TcpServer(String bossGroupName, String workerGroupName) {
		super();
		this.bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory(bossGroupName));
		this.workerGroup = new NioEventLoopGroup(0, new DefaultThreadFactory(bossGroupName));
	}

	public void bind(int port, ChannelInitializer<SocketChannel> adapter) {
		try {
			new ServerBootstrap().group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
					.option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO)).childHandler(adapter)
					.bind(port).sync();
		} catch (InterruptedException e) {
			log.error("", e);
		}
	}

	public void shutdown() {
		bossGroup.shutdownGracefully();
		workerGroup.shutdownGracefully();
	}
}